package dev.loong.boot3.service.impl;

import dev.loong.boot3.dao.ProductDao;
import dev.loong.boot3.dao.PurchaseRecordDao;
import dev.loong.boot3.pojo.ProductPo;
import dev.loong.boot3.pojo.PurchaseRecordPo;
import dev.loong.boot3.service.PurchaseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;

@Service
public class PurchaseServiceImpl implements PurchaseService {
    private final ProductDao productDao;
    private final PurchaseRecordDao purchaseRecordDao;
    @Autowired
    public PurchaseServiceImpl(ProductDao productDao, PurchaseRecordDao purchaseRecordDao) {
        this.productDao = productDao;
        this.purchaseRecordDao = purchaseRecordDao;
    }
    @Override
    @Transactional
    public boolean purchase(Long userId, Long productId, int quantity) {
        for (int i = 0; i < 3; i++) {
            // 获取产品
            var product = productDao.getProduct(productId);
            // 查询库存
            if (product.getStock() < quantity) {
                return false;
            }
            var version = product.getVersion();
            // 扣减库存
            var result = productDao.decreaseProduct(productId, quantity, version);
            if (result == 0) {
                return false;
            }
            // 创建购买记录
            var pr = initPurchaseRecord(userId, product, quantity);
            int ret = purchaseRecordDao.insertPurchaseRecord(pr);
            if (ret > 0) {
                return true;
            }
        }
        return false;
    }

    private PurchaseRecordPo initPurchaseRecord(Long userId, ProductPo product, int quantity) {
        var purchaseRecord = new PurchaseRecordPo();
        purchaseRecord.setNote("购买日志，时间：" + System.currentTimeMillis());
        purchaseRecord.setUserId(userId);
        purchaseRecord.setProductId(product.getId());
        purchaseRecord.setQuantity(quantity);
        purchaseRecord.setPrice(product.getPrice());
        purchaseRecord.setSum(purchaseRecord.getPrice() * quantity);
        return purchaseRecord;
    }
}
